package com.ctgu.demo03.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.demo03.entity.ProductsEntity;
import com.ctgu.demo03.entity.StatisticsEntity;
import com.ctgu.demo03.service.ProductsService;
import com.ctgu.demo03.service.StatisticsService;
import com.ctgu.demo03.mapper.StatisticsMapper;
import com.ctgu.demo03.utils.ApiResult;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.PostConstruct;
import javax.xml.crypto.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
* @author Alex2
* @description 针对表【t_statistics】的数据库操作Service实现
* @createDate 2025-03-11 22:25:48
*/
@Service
public class StatisticsServiceImpl extends ServiceImpl<StatisticsMapper, StatisticsEntity>
    implements StatisticsService {

    /**
     * @Author: Alex
     * @Description: 插入修改数量
     */
    @Override
    public ApiResult insertStatistic(String name, Integer modify) {
        StatisticsEntity statistics = lambdaQuery().eq(StatisticsEntity::getName, name).one();
        if (statistics != null) {
            return ApiResult.error("该统计项已存在，插入失败");
        }
        StatisticsEntity statisticsEntity = new StatisticsEntity(null, name, modify, LocalDateTime.now());
        boolean save = save(statisticsEntity);
        if (!save) {
            return ApiResult.error("插入失败");
        }
        return ApiResult.success("插入成功");
    }

    /**
     * @Author: Alex
     * @Description: 时间戳实现乐观锁
     */
    @Override
    public ApiResult updateModify(Integer id, Integer modify) {
        StatisticsEntity statistics = lambdaQuery().eq(StatisticsEntity::getId, id).one();
        if (statistics == null) {
            return ApiResult.error("统计数据不存在");
        }
        StatisticsService statisticsServiceProxy = (StatisticsService) AopContext.currentProxy();
        return statisticsServiceProxy.updateModifyTransactional(id, modify, statistics.getLastUpdateTime());
    }

    @Transactional
    @Override
    public ApiResult updateModifyTransactional(Integer id, Integer modify, LocalDateTime lastUpdateTime) {
        boolean update = lambdaUpdate()
                .eq(StatisticsEntity::getId, id)
                .eq(StatisticsEntity::getLastUpdateTime, lastUpdateTime)
                .set(StatisticsEntity::getModify, modify)
                .set(StatisticsEntity::getLastUpdateTime, LocalDateTime.now())
                .update();
        if (!update) {
            return ApiResult.error("更新失败，数据已被修改，请重试");
        }
        return ApiResult.success("更新成功");
    }
}